<template>
  <div>
    <div style="display: flex;justify-content: space-between;margin-bottom: 30px">
      <el-autocomplete  style="width: 80%; " v-model="address" @select="getLocations" :fetch-suggestions="querySearch" placeholder="请输入详细地址" :trigger-on-focus="false" />
      
      <div style="width: 19%;text-align: right;" ><el-button type="primary" @click="getLocations"> 搜索 </el-button></div>
    </div>
    <div id="amp-container" />
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, toRefs, inject, defineProps } from 'vue'
import { getstaffdetail } from '@/api/employe/storemanagement/sensitiveWord'
import { getLoaction, getGeocoder, getsuggestion } from '@/api/customerbulletin/bulleinManage'
import router from '@/router'
import { useRouter, useRoute } from 'vue-router' 
import { ElMessage } from 'element-plus'
import { loadJS } from '@/utils/utils'

const props = withDefaults(
  defineProps<{
    address: any,
    store_address:any
  }>(),
  {
    address: '',
    store_address:''
  }
)
const $api: any = inject('$api')
const address = ref('')

const route = useRoute()
let pageType = route.query.type
const dataMap = reactive({
  map: '',
  markerLayer: '',
  latitude: '', //纬度
  lngitude: '' //经度
})

const emit = defineEmits(['searchresult','getLocat'])
onMounted(() => {
  loadJS('https://map.qq.com/api/gljs?v=1.exp&key=FXQBZ-BK464-2NGUQ-XTB2B-2Z3EF-LNF3C').then(()=>{
    const TMap = (window as any).TMap

    init()
    pageType = route.query.type

    console.log(pageType, 'pageyreahiu')
    if (pageType == 'edit') {
      //编辑
      address.value = props.store_address
    }else{
      getLocation()
    }
  })
})
const init = () => {
  let center = new TMap.LatLng(dataMap.latitude, dataMap.lngitude)
  dataMap.map = new TMap.Map(document.getElementById('amp-container'), {
    center: center, //设置地图中心点坐标
    zoom: 11, //设置地图缩放级别
    viewMode: '2D'
  })
  ;(dataMap.map as any).on('click', clickHandler) // 绑定点击地图获取地理位置的事件
  markerLayer() // 标记地图
}
// 重载地图
const reloadMap = () => {
  ;(document.getElementById('amp-container') as any).innerHTML = ''
  dataMap.markerLayer = ''
  let center = new TMap.LatLng(dataMap.latitude, dataMap.lngitude)
  dataMap.map = new TMap.Map(document.getElementById('amp-container'), {
    center: center, //设置地图中心点坐标
    viewMode: '2D'
  })
  markerLayer()
}
const getLocation = async () => {
  try {
    let params = {
      // ip:(window as any ).returnCitySN['cip'],
      // key: 'FXQBZ-BK464-2NGUQ-XTB2B-2Z3EF-LNF3C' // 填申请到的腾讯key
    }
    getLoaction(params)
      .then((result: any) => {
        console.log(result, '2222获取经纬度222222222')
        dataMap.latitude = result.result.location.lat
        dataMap.lngitude = result.result.location.lng
        emit('getLocat',dataMap)
        ;(dataMap.map as any).setCenter(new TMap.LatLng(dataMap.latitude, dataMap.lngitude))
        reloadMap()
      })
      .catch((err: any) => {
        console.log(err, '===失败')
        // throw new Error(err)
      })
  } catch (e) {
    console.log(e)
  }
}
// 点击获取经纬度
const clickHandler = (evt: any) => {
  dataMap.latitude = evt.latLng.getLat().toFixed(6)
  dataMap.lngitude = evt.latLng.getLng().toFixed(6)
  ;(dataMap.map as any).setCenter(new TMap.LatLng(dataMap.latitude, dataMap.lngitude))
  reloadMap()
}
//标记地图
const markerLayer = () => {
  dataMap.markerLayer = new TMap.MultiMarker({
    map: dataMap.map, //指定地图容器
    //样式定义
    styles: {
      //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
      myStyle: new TMap.MarkerStyle({
        width: 25, // 点标记样式宽度（像素）
        height: 35, // 点标记样式高度（像素）
        // "src": '../../assets/logo.png',  //图片路径
        background: 'pink',
        //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
        anchor: { x: 16, y: 32 }
      })
    },
    //点标记数据数组
    geometries: [
      {
        id: '1', //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
        styleId: 'myStyle', //指定样式id
        position: new TMap.LatLng(dataMap.latitude, dataMap.lngitude) //点标记坐标位置
      }
    ]
  })
}
// 获取搜索经纬度
const getLocations = async () => {
  try {
    let params = {
      key: 'FXQBZ-BK464-2NGUQ-XTB2B-2Z3EF-LNF3C', // 填申请到的腾讯key
      address: address.value //具体的地址
    }
    getGeocoder(params)
      .then((result: any) => {
       
        dataMap.latitude = result.result.location.lat
        dataMap.lngitude = result.result.location.lng
        emit('searchresult', result.result, address.value)
        console.log(address.value,result, 2222222222222,dataMap)
        ;(dataMap.map as any).setCenter(new TMap.LatLng(dataMap.latitude, dataMap.lngitude))
        reloadMap()
      })
      .catch((err: any) => {
         ElMessage.error('当前地址不存在，请重新输入门店地址')
         address.value=''
        console.log(err, '===111失败')
        // throw new Error(err)
      })
  } catch (error) {
    console.log(error)
  }
}
const querySearch = async (queryString: string, cb: any) => {
  try {
    let params = {
      keyword: queryString,
      key: 'FXQBZ-BK464-2NGUQ-XTB2B-2Z3EF-LNF3C' // 填申请到的腾讯key
    }
    getsuggestion(params)
      .then((data: any) => {
        const results = data.data.map((item: any) => {
          let obj = {
            value: item.address,
            address: item.address
          }
          return obj
        })
        cb(results)
      })
      .catch((err: any) => {
        console.log(err, '===失败')
        // throw new Error(err)
      })
  } catch (e) {
    console.log(e)
  }
}
</script>
